import { UserModule } from './user'
import { VuexModule, Module, Action, Mutation, getModule } from 'vuex-module-decorators'
import store from '@/store'
import { getToken, reomveToken, setToken } from '@/service/auth'
import request from '@/service/request'
import { IUser } from '@/service/user'

export interface IAuthState {
    token: string
}
export interface ILoginResponse extends IAuthState {
    user: IUser
}

@Module({
    dynamic: true,
    store,
    name: 'auth'
})
class Auth extends VuexModule implements IAuthState {
    public token: string = getToken() || ''

    @Mutation
    SET_TOKEN(token: string) {
        this.token = token
    }

    @Action
    async Login(userInfo: { username: string; password: string }) {
        // let { username, password } = userInfo
        const {
            data: { token, user }
        } = await request.post<{
            data: ILoginResponse
        }>('/api/login', userInfo)
        // 更新store
        this.SET_TOKEN(token)
        // 更新本地保存
        setToken(token)
        UserModule.UpdateUser(user)
    }

    @Action
    async Logout() {
        // 清除token
        this.SET_TOKEN('')
        reomveToken()
        // 清除用户数据
        UserModule.ResetUser()
    }
}

export const AuthModule = getModule(Auth)
